
from pptx import Presentation
import pandas as pd
from pygtrans import Translate
from pathlib import Path
import os

import PySimpleGUI as sg
from __version__ import __version__

BASE_DIR = Path(__file__).resolve().parent
OUTPUT_DIR = BASE_DIR / 'output'

def show():
    # 定义窗口的布局
    layout = [
        [sg.Text('请选择需要翻译的PPT文件：', font=('微软雅黑', 12))],
        [
            sg.InputText(font=('微软雅黑', 12), key='-IN-', size=(30, 20), pad=(10, 10)),
            sg.FileBrowse('···', font=('微软雅黑', 11))],
        [
            sg.Button('Start', font=('微软雅黑', 11), key='-START-', enable_events=True),
            # sg.Button('View', font=('微软雅黑', 11), key='-VIEW-')
        ]
    ]

    # 创建窗口
    window = sg.Window(f'PPT Translator v{__version__}', layout)

    while True:
        event, values = window.read()

        try:
            

            if event in (None, 'Cancel'):
                break
            elif event == '-START-':
                if not OUTPUT_DIR.exists():
                    OUTPUT_DIR.mkdir()

                ppt_file = values['-IN-']

                if not ppt_file.endswith('.pptx'):
                    sg.popup_error('Error', '请选择PPT文件', font=('微软雅黑', 12))
                    continue

                ppt_file = Path(ppt_file)
                texts_li = get_texts(ppt_file=ppt_file, content_type=1)
                export(texts_li, OUTPUT_DIR / 'output.xlsx')

                sg.popup_notify('PPT翻译完成', title='通知')

                os.startfile(OUTPUT_DIR)


        except Exception as e:
            print(e)
            sg.PopupError('Error', e)

    # 关闭窗口
    window.close()



def get_texts(ppt_file, content_type: int=1):

    # 读取PPT文件
    m_ppt = Presentation(ppt_file)

    # 获取所有页数
    print(f'一共{len(m_ppt.slides)}页')

    texts_all = []
    for n, slide in enumerate(m_ppt.slides, 1):

        # 正在处理第几页
        print(f'正在处理第{n}页')
        texts_all.append(f'-第{n}页-')

        if content_type == 0:
            # 获取备注
            notes_slide = slide.notes_slide
            if notes_slide:
                note_text = notes_slide.notes_text_frame.text
                print(f"Slide {slide.slide_id}: {note_text}")
                texts_all.append('备注：' + note_text.strip().replace('\n', ' '))

            continue

        for shape in slide.shapes:

            # 获取文本
            if shape.has_text_frame:
                for paragraph in shape.text_frame.paragraphs:
                    para_text = ''
                    for content in paragraph.runs:
                        para_text += content.text
                    # if para_text:
                        # print(para_text.strip().replace('\n', ' '))
                    texts_all.append(para_text.strip())

            # 获取表格内容
            if shape.has_table:
                for row in shape.table.rows:
                    for cell in row.cells:
                        cell_text = ''
                        for paragraph in cell.text_frame.paragraphs:
                            for content in paragraph.runs:
                                cell_text += content.text
                        # print(cell_text.strip())
                        texts_all.append(cell_text.strip().replace(' ', ''))

            # 获取组内文本
            if shape.shape_type.name == 'GROUP':
                for shp in shape.shapes:
                    if shp.has_text_frame:
                        for paragraph in shp.text_frame.paragraphs:
                            para_text = ''
                            for content in paragraph.runs:
                                para_text += content.text

                            texts_all.append(para_text.strip())


        print('-' * 30)

    texts_all = [x.replace('▍', '') for x in texts_all if x]
    print(texts_all)
    return texts_all


# 翻译成英文

def translate(texts_list):
    translator = Translate()
    data = translator.translate(texts_list, target='en')
    en_list = [x.translatedText for x in data]
    return en_list


def export(texts_list, out_file):
    trans_list = translate(texts_list)
    df = pd.DataFrame(data={'CN': texts_list, 'EN': trans_list})
    df.to_excel(out_file, index=False)


if __name__ == '__main__':
    # texts_li = get_texts(ppt_file='人工智能安全风险应对-20240913-V1-无视频(1).pptx', content_type=1)
    # export(texts_li)

    show()